package com.bazaaroid.server.gae.util;

public class NumberUtil {

	public static Integer stringToInt(String str) {
		if(str == null) {
			return null;
		}

		try {
			return Integer.valueOf(str);
		}
		catch (NumberFormatException ex) {
			return null;
		}
	}

	public static Double stringToDouble(String str) {
		if(str == null) {
			return null;
		}

		try {
			return Double.valueOf(str);
		} catch (NumberFormatException ex) {
			return null;
		}
	}

	public static Float stringToFloat(String str) {
		if(str == null) {
			return null;
		}

		try {
			return Float.valueOf(str);
		} catch (NumberFormatException ex) {
			return null;
		}
	}

	public static Long stringToLong(String str) {
		if(str == null) {
			return null;
		}

		try {
			return Long.valueOf(str);
		}
		catch (NumberFormatException ex) {
			return null;
		}
	}

	public static double toDouble(Object object, double defaultValue) {
		if(object == null) {
			return defaultValue;
		}
		else if(object instanceof Number) {
			return ((Number) object).doubleValue();
		}
		else if(object instanceof String) {
			try {
				return Double.parseDouble((String) object);
			}
			catch (NumberFormatException ex) {
				return defaultValue;
			}
		}

		return defaultValue;
	}

	public static int toInt(Object object, int defaultValue) {
		if(object == null) {
			return defaultValue;
		}
		else if(object instanceof Number) {
			return ((Number) object).intValue();
		}
		else if(object instanceof String) {
			try {
				return Integer.parseInt((String) object);
			}
			catch (NumberFormatException ex) {
				return defaultValue;
			}
		}

		return defaultValue;
	}

	public static int toInt(Object object) {
		return toInt(object, 0);
	}

}
